//引入 koa模块

var Koa = require('koa'),
    router = require('koa-router')(),
    path = require('path'),
    render = require('koa-art-template'),
    static = require('koa-static'),
    session = require('koa-session'),
    sd = require('silly-datetime'),
    jsonp = require('koa-jsonp'),
    cors = require('koa2-cors'),
    bodyParser = require('koa-bodyparser');
const url = require('url');
const axios = require('axios');
const cheerio = require('cheerio');
const iconv = require('iconv-lite');

const baseUrl = 'http://www.ibiqu.org'

// 实例化
const app = new Koa();
const DB = require('./module/db');

// 配置jsonp的中间件
app.use(jsonp());

// 允许跨域
app.use(cors());

//配置session的中间件
app.keys = ['some secret hurr'];
const CONFIG = {
    key: 'koa:sess',
    maxAge: 864000,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: true,
    /*每次请求都重新设置session*/
    renew: false,
};
app.use(session(CONFIG, app));

//配置post提交数据的中间件
app.use(bodyParser());

//配置 静态资源的中间件
app.use(static(__dirname + '/public'));

//配置模板引擎
console.log(path.join(__dirname, 'views'))
render(app, {
    root: path.join(__dirname, 'views'),
    extname: '.html',
    debug: process.env.NODE_ENV !== 'production',
    // dateFormat: dateFormat = function(value) {
    //     return sd.format(value, 'YYYY-MM-DD HH:mm');
    // } /*扩展模板里面的方法*/
});
// 配置中间件 获取url地址
router.use(async (ctx, next) => {
    // 模板引擎配置全局的变量
    ctx.state.__HOST__ = "http://" + ctx.request.header.host;

    let pathname = url.parse(ctx.request.url).pathname.substring(1);

    let splitUrl = pathname.split('/');
    // 添加全局对象
    ctx.state.G = {
        url: splitUrl,
        userinfo: ctx.session.userinfo,
        prevPage: ctx.request.header['referer']
    }
    // 登录权限判断
    // if (ctx.session.userinfo) {
    await next();
    // } else {
    //     if (pathname === 'admin/login' || pathname === 'admin/login/doLogin' || pathname === 'admin/login/code') {
    //         await next();
    //     } else {
    //         ctx.redirect('/admin/login');
    //     }
    // }
})


router.get('/', async (ctx) => {
    let result = await DB.find('user', {});
    console.log(result)
    await ctx.render('index', {});
})

router.get('/search', async (ctx) => {
    await ctx.render('search', {
        bookName: '',
        list: []
    });
})
router.post('/search', async (ctx) => {
    const bookName = ctx.request.body.bookName
    let addr = '';
    let list = []
    if (bookName) {
        list = await getBookUrl(bookName)
    }
    console.log(addr)
    await ctx.render('search', {
        bookName,
        list
    });
})

/**
 * 根据书名搜索笔趣阁
 * @param {string} bookName 
 */
const getBookUrl = async (bookName) => {
    const { data } = await axios({
        method: 'get',
        url: `${baseUrl}/modules/article/search.php?searchkey=${bookName}`,
        responseType: 'arraybuffer'
    })
    const html = iconv.decode(data, 'gbk')
    const $ = cheerio.load(html, { decodeEntities: false })
    const el = $('#hotcontent table.grid tbody>tr')
    const list = []
    if (el.length) {
        for (let index = 0; index < el.length; index++) {
            const element = el[index];
            const bookName = $($(element).find('td')[0]).text()
            const addr = $($(element).find('td:first-child a')).attr('href')
            const auther = $($(element).find('td')[2]).text()
            if(bookName && auther){
                list.push({
                    bookName,
                    auther,
                    addr
                })
            }
        }
    }
    return list
}

// 抓取小说章节与内容
router.get('/doAdd', async (ctx) => {
    const url = baseUrl+ctx.request.query.addr
    const bookName = ctx.request.query.bookName
    const { data } = await axios({
        method: 'get',
        url: url,
        responseType: 'arraybuffer'
    })
    console.log(data)
    const html = iconv.decode(data, 'gbk')
    const $ = cheerio.load(html, { decodeEntities: false })
    const el = $('.box_con #list dl dd')
    const list = []
    for (let index = 0; index < el.length; index++) {
        const element = el[index];
        const text = $(element).text()
        if(text.indexOf('章') !== -1){
            list.push(text)
        }
    }
    await ctx.render('wrapper', {
        bookName,
        list
    });
})

// 启动路由
app.use(router.routes()).use(router.allowedMethods());

app.listen(3003);

console.log('http://localhost:3003');
